/**
 * 翻译模块
 * 支持 OpenAI 和有道翻译两种引擎
 */

class TranslationEngine {
    constructor(config) {
        this.config = config;
        this.cache = new Map();
    }

    /**
     * 生成缓存键
     */
    getCacheKey(text, from, to, engine) {
        return `${engine}:${from}:${to}:${this.hashString(text)}`;
    }

    /**
     * 字符串哈希
     */
    hashString(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return hash.toString();
    }

    /**
     * 检查缓存
     */
    checkCache(text, from, to, engine) {
        if (!this.config.cacheEnabled) {
            return null;
        }

        const key = this.getCacheKey(text, from, to, engine);
        return this.cache.get(key) || null;
    }

    /**
     * 保存到缓存
     */
    saveToCache(text, from, to, engine, result) {
        if (!this.config.cacheEnabled) {
            return;
        }

        const key = this.getCacheKey(text, from, to, engine);
        this.cache.set(key, result);

        // 限制缓存大小
        if (this.cache.size > 1000) {
            const firstKey = this.cache.keys().next().value;
            this.cache.delete(firstKey);
        }
    }

    /**
     * 分割长文本
     */
    splitText(text, maxLength = 2000) {
        if (text.length <= maxLength) {
            return [text];
        }

        const chunks = [];
        let currentChunk = '';
        const sentences = text.split(/[.!?。！？\n]+/);

        for (const sentence of sentences) {
            if (currentChunk.length + sentence.length + 1 <= maxLength) {
                currentChunk += (currentChunk ? '. ' : '') + sentence;
            } else {
                if (currentChunk) {
                    chunks.push(currentChunk);
                }
                currentChunk = sentence;
            }
        }

        if (currentChunk) {
            chunks.push(currentChunk);
        }

        return chunks;
    }

    /**
     * 合并翻译结果
     */
    mergeTranslations(translations) {
        return translations.join(' ');
    }
}

/**
 * OpenAI 翻译引擎
 */
class OpenAITranslator extends TranslationEngine {
    constructor(config) {
        super(config);
        this.baseUrl = config.openaiBaseUrl || 'https://api.openai.com/v1';
        this.apiKey = config.openaiApiKey;
        this.model = config.openaiModel || 'gpt-3.5-turbo';
    }

    /**
     * 翻译文本
     */
    async translate(text, from = 'auto', to = 'zh-CN') {
        try {
            // 检查缓存
            const cached = this.checkCache(text, from, to, 'openai');
            if (cached) {
                return cached;
            }

            // 如果文本太长，分割处理
            if (text.length > this.config.maxTextLength) {
                const chunks = this.splitText(text, this.config.maxTextLength);
                const translations = [];

                for (const chunk of chunks) {
                    const translation = await this.translateChunk(chunk, from, to);
                    translations.push(translation);
                }

                const result = this.mergeTranslations(translations);
                this.saveToCache(text, from, to, 'openai', result);
                return result;
            }

            // 翻译单个文本块
            const result = await this.translateChunk(text, from, to);
            this.saveToCache(text, from, to, 'openai', result);
            return result;

        } catch (error) {
            console.error('OpenAI translation error:', error);
            throw new Error(`OpenAI 翻译失败: ${error.message}`);
        }
    }

    /**
     * 翻译单个文本块
     */
    async translateChunk(text, from, to) {
        const languageMap = {
            'zh-CN': '简体中文',
            'zh-TW': '繁体中文',
            'en': '英语',
            'ja': '日语',
            'ru': '俄语',
            'auto': '自动检测'
        };

        const targetLanguage = languageMap[to] || '简体中文';
        const sourceLanguage = from === 'auto' ? '自动检测' : (languageMap[from] || '英语');

        const prompt = `请将以下${sourceLanguage}的算法竞赛题目内容翻译成${target语言}。

要求：
1. 保持代码块、公式、数字不变
2. 保持原文的专业术语准确性
3. 保持段落结构清晰
4. 只返回翻译结果，不要添加额外说明

原文：
${text}

翻译：`;

        const response = await fetch(`${this.baseUrl}/chat/completions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.apiKey}`
            },
            body: JSON.stringify({
                model: this.model,
                messages: [{ role: 'user', content: prompt }],
                max_tokens: Math.max(text.length * 2, 500),
                temperature: 0.3
            }),
            signal: AbortSignal.timeout(this.config.requestTimeout * 1000)
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error?.message || `HTTP ${response.status}`);
        }

        const data = await response.json();
        return data.choices[0]?.message?.content?.trim() || '';
    }
}

/**
 * 有道翻译引擎
 */
class YoudaoTranslator extends TranslationEngine {
    constructor(config) {
        super(config);
        this.appKey = config.youdaoApiKey;  // 应用ID
        this.appSecret = config.youdaoAppSecret;  // 应用密钥
        this.apiUrl = 'https://openapi.youdao.com/api';
    }

    /**
     * 翻译文本
     */
    async translate(text, from = 'auto', to = 'zh-CN') {
        try {
            // 检查缓存
            const cached = this.checkCache(text, from, to, 'youdao');
            if (cached) {
                return cached;
            }

            // 有道翻译语言映射
            const youdaoLanguageMap = {
                'auto': 'auto',
                'en': 'en',
                'zh-CN': 'zh-CHS',
                'zh-TW': 'zh-CHT',
                'ja': 'ja',
                'ru': 'ru'
            };

            const youdaoFrom = youdaoLanguageMap[from] || 'auto';
            const youdaoTo = youdaoLanguageMap[to] || 'zh-CHS';

            // 如果文本太长，分割处理
            if (text.length > this.config.maxTextLength) {
                const chunks = this.splitText(text, this.config.maxTextLength);
                const translations = [];

                for (const chunk of chunks) {
                    const translation = await this.translateChunk(chunk, youdaoFrom, youdaoTo);
                    translations.push(translation);
                }

                const result = this.mergeTranslations(translations);
                this.saveToCache(text, from, to, 'youdao', result);
                return result;
            }

            // 翻译单个文本块
            const result = await this.translateChunk(text, youdaoFrom, youdaoTo);
            this.saveToCache(text, from, to, 'youdao', result);
            return result;

        } catch (error) {
            console.error('Youdao translation error:', error);
            throw new Error(`有道翻译失败: ${error.message}`);
        }
    }

    /**
     * 翻译单个文本块
     */
    async translateChunk(text, from, to) {
        // 预处理文本，处理特殊字符
        const processedText = this.preprocessText(text);
        console.log('🔧 Text preprocessed:', {
            originalLength: text.length,
            processedLength: processedText.length,
            hasSpecialChars: /[\u0000-\u001F\u007F-\u009F\u2000-\u200F\u2028-\u202F\u205F-\u206F]/.test(text),
            hasMarkdown: /[`*#\[\]()_~\\]/.test(text),
            hasLatex: /\\[a-zA-Z]+|\\[^\w\s]/.test(text)
        });

        // 生成v3版本的签名参数
        const salt = this.generateUUID();
        const curtime = Math.floor(Date.now() / 1000).toString();
        const sign = await this.generateSignV3(processedText, salt, curtime);

        console.log('🔐 Generated v3 signature:', {
            salt: salt,
            curtime: curtime,
            signLength: sign.length,
            signPreview: sign.substring(0, 20) + '...'
        });

        // 构建请求参数
        const params = new URLSearchParams();
        params.append('q', processedText);
        params.append('from', from);
        params.append('to', to);
        params.append('appKey', this.appKey);
        params.append('salt', salt);
        params.append('curtime', curtime);
        params.append('signType', 'v3');
        params.append('sign', sign);

        console.log('🌐 Sending Youdao API request:', {
            url: this.apiUrl,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            from: from,
            to: to,
            textLength: processedText.length,
            textPreview: processedText.substring(0, 100) + (processedText.length > 100 ? '...' : ''),
            appKey: this.appKey.substring(0, 8) + '...',
            appKeyLength: this.appKey.length,
            salt: salt,
            curtime: curtime,
            signType: 'v3',
            signLength: sign.length,
            signPreview: sign.substring(0, 20) + '...',
            fullRequestBody: params.toString().substring(0, 200) + (params.toString().length > 200 ? '...' : '')
        });

        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), this.config.requestTimeout * 1000);

        try {
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params.toString(),
                signal: controller.signal
            });

            clearTimeout(timeoutId);
            console.log('📥 Youdao API response status:', response.status, response.statusText);

            if (!response.ok) {
                const errorText = await response.text();
                console.error('❌ Youdao API request failed:', {
                    status: response.status,
                    statusText: response.statusText,
                    errorText: errorText
                });
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            console.log('📋 Youdao API response data:', data);

            if (data.errorCode !== '0') {
                const errorMessages = {
                    '108': 'appKey无效',
                    '202': '签名检验失败',
                    '301': '账户余额不足',
                    '411': '访问频率受限',
                    '501': '请求的query为空',
                    '901': '翻译语种不支持'
                };
                const errorMsg = errorMessages[data.errorCode] || `API Error: ${data.errorCode}`;
                console.error('❌ Youdao API error:', {
                    errorCode: data.errorCode,
                    errorMsg: errorMsg,
                    fullResponse: data
                });
                throw new Error(errorMsg);
            }

            const translation = data.translation?.[0] || '';
            console.log('✅ Youdao translation successful:', {
                originalLength: processedText.length,
                translationLength: translation.length
            });

            return translation;

        } catch (error) {
            clearTimeout(timeoutId);
            if (error.name === 'AbortError') {
                console.error('⏰ Youdao API request timeout');
                throw new Error(`请求超时 (${this.config.requestTimeout}秒)`);
            }
            throw error;
        }
    }

    /**
     * 预处理文本，处理特殊字符
     */
    preprocessText(text) {
        if (!text || typeof text !== 'string') {
            return text;
        }

        console.log('🔧 Preprocessing text:', {
            originalLength: text.length,
            containsNull: text.includes('\u0000'),
            containsControl: /[\u0000-\u001F\u007F-\u009F]/.test(text),
            containsBidi: /[\u2000-\u200F\u2028-\u202F\u205F-\u206F]/.test(text)
        });

        let processed = text;

        // 1. 移除空字符和控制字符
        processed = processed.replace(/\u0000/g, ''); // 移除空字符
        processed = processed.replace(/[\u0001-\u001F\u007F-\u009F]/g, ''); // 移除控制字符

        // 2. 处理双向文本控制字符
        processed = processed.replace(/[\u200B-\u200F\u202A-\u202E\u2060-\u206F]/g, '');

        // 3. 处理可能的编码问题
        try {
            processed = decodeURIComponent(encodeURIComponent(processed));
        } catch (error) {
            console.warn('⚠️ Text encoding issue, using original:', error);
        }

        // 4. 处理过长的连续空白字符
        processed = processed.replace(/\s{10,}/g, ' '.repeat(3));

        // 5. 处理可能的HTML实体（但保留代码块中的实体）
        processed = processed.replace(/&nbsp;/g, ' ');
        processed = processed.replace(/&quot;/g, '"');
        processed = processed.replace(/&amp;/g, '&');
        processed = processed.replace(/&lt;/g, '<');
        processed = processed.replace(/&gt;/g, '>');

        // 6. 确保文本不为空
        if (!processed.trim()) {
            console.warn('⚠️ Text became empty after preprocessing, using fallback');
            return text.length > 100 ? text.substring(0, 100) + '...' : text;
        }

        console.log('✅ Text preprocessed successfully:', {
            originalLength: text.length,
            processedLength: processed.length,
            ratio: (processed.length / text.length).toFixed(2)
        });

        return processed;
    }

    /**
     * 生成v3版本的有道签名
     */
    async generateSignV3(query, salt, curtime) {
        // sign = sha256(appKey + input(q) + salt + curtime + appSecret)
        const str = this.appKey + this.getInput(query) + salt + curtime + this.appSecret;
        return await this.sha256(str);
    }

    /**
     * 生成UUID（用于salt）
     */
    generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    /**
     * 获取input文本（处理数组情况）
     */
    getInput(query) {
        // 如果query是数组，连接所有元素
        if (Array.isArray(query)) {
            return query.join('');
        }
        return query;
    }

    /**
     * 生成有道签名（v2版本，已弃用）
     */
    generateSign(query, salt) {
        const str = this.appSecret + query + salt;
        return this.sha256(str);
    }

    /**
     * SHA256 哈希
     */
    async sha256(message) {
        const encoder = new TextEncoder();
        const data = encoder.encode(message);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }
}

/**
 * 翻译管理器
 */
class TranslationManager {
    constructor() {
        this.currentTranslator = null;
    }

    /**
     * 初始化翻译器
     */
    async initialize() {
        try {
            const config = await chrome.storage.sync.get({
                translationEngine: 'openai',
                openaiApiKey: '',
                openaiBaseUrl: 'https://api.openai.com/v1',
                openaiModel: 'gpt-3.5-turbo',
                youdaoApiKey: '',
                youdaoAppSecret: '',
                maxTextLength: 2000,
                requestTimeout: 30,
                cacheEnabled: true,
                debugMode: false
            });

            // 检查配置完整性
            if (config.translationEngine === 'openai' && !config.openaiApiKey) {
                throw new Error('OpenAI API Key 未配置');
            }

            if (config.translationEngine === 'youdao' && (!config.youdaoApiKey || !config.youdaoAppSecret)) {
                throw new Error('有道翻译配置不完整');
            }

            // 创建对应的翻译器
            if (config.translationEngine === 'openai') {
                this.currentTranslator = new OpenAITranslator(config);
            } else if (config.translationEngine === 'youdao') {
                this.currentTranslator = new YoudaoTranslator(config);
            } else {
                throw new Error('不支持的翻译引擎');
            }

            this.config = config;
            return true;

        } catch (error) {
            console.error('Failed to initialize translator:', error);
            throw error;
        }
    }

    /**
     * 翻译文本
     */
    async translate(text, from = 'auto', to = 'zh-CN') {
        if (!this.currentTranslator) {
            await this.initialize();
        }

        if (!this.currentTranslator) {
            throw new Error('翻译器未初始化');
        }

        return await this.currentTranslator.translate(text, from, to);
    }

    /**
     * 检查是否已配置
     */
    async isConfigured() {
        try {
            const config = await chrome.storage.sync.get({
                translationEngine: 'openai',
                openaiApiKey: '',
                youdaoApiKey: '',
                youdaoAppSecret: ''
            });

            if (config.translationEngine === 'openai') {
                return !!config.openaiApiKey;
            } else if (config.translationEngine === 'youdao') {
                return !!(config.youdaoApiKey && config.youdaoAppSecret);
            }

            return false;
        } catch (error) {
            console.error('Failed to check configuration:', error);
            return false;
        }
    }

    /**
     * 获取当前配置
     */
    async getCurrentConfig() {
        return await chrome.storage.sync.get({
            translationEngine: 'openai',
            sourceLanguage: 'auto',
            targetLanguage: 'zh-CN',
            displayMode: 'below',
            autoTranslate: false
        });
    }

    /**
     * 快速测试API连接
     */
    async quickTestAPI() {
        console.log('🧪 Starting quick API test...');

        if (!this.currentTranslator) {
            await this.initialize();
        }

        if (!this.currentTranslator) {
            throw new Error('翻译器未初始化');
        }

        const testText = 'Hello, this is a test.';
        console.log('🧪 Testing with text:', testText);

        try {
            const startTime = Date.now();
            const result = await this.currentTranslator.translate(testText, 'en', 'zh-CN');
            const duration = Date.now() - startTime;

            console.log('✅ API test successful:', {
                duration: duration,
                original: testText,
                translated: result
            });

            return { success: true, result, duration };
        } catch (error) {
            console.error('❌ API test failed:', error);
            return { success: false, error: error.message };
        }
    }
}

// 导出翻译管理器
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        TranslationManager,
        OpenAITranslator,
        YoudaoTranslator
    };
} else {
    window.TranslationManager = TranslationManager;
    window.OpenAITranslator = OpenAITranslator;
    window.YoudaoTranslator = YoudaoTranslator;
}